package com.cc.util;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author CHENCHEN
 * @company 北京学佳澳教育科技
 * @create 2023-03-22 13:32
 */
@Component
public class RedisUtil {

    private final RedisTemplate<String, String> redisTemplate;

    public RedisUtil(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }



    // String 类型
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, String value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    // Hash 类型
    public <HK, HV> void putHash(String key, HK hashKey, HV value) {
        redisTemplate.opsForHash().put(key, String.valueOf(hashKey), value);
    }

    public <HK, HV> HV getHash(String key, HK hashKey) {
        return (HV) redisTemplate.opsForHash().get(key, String.valueOf(hashKey));
    }

    public <HK, HV> Map<HK, HV> getHashEntries(String key) {
        return (Map<HK, HV>) redisTemplate.opsForHash().entries(key);
    }

    public Long hLen(String key) {
        return redisTemplate.opsForHash().size(key);
    }

    public void deleteHashKeys(String key, Object... hashKeys) {
        redisTemplate.opsForHash().delete(key, hashKeys);
    }

    // 删除键
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    // 删除多个键
    public void deleteKeys(List<String> keys) {
        redisTemplate.delete(keys);
    }

    /*public void incrementDefault(String key) {
        redisTemplate.opsForValue().set(key, "1");
    }*/

    public void increment(String key) {
        redisTemplate.opsForValue().increment(key);
    }

    // 检查键是否存在
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
}